package com.example.administrator.view;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Set;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private WebView my_webView;
    private Button btn_callJS;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        my_webView = findViewById(R.id.my_webView);
        btn_callJS = findViewById(R.id.btn_callJS);
        //在Android中允许页面的js运行
        WebSettings webSettings = my_webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);//允许打开新窗口
        //字符问题
        webSettings.setDefaultTextEncodingName("utf-8");

        //my_webView.loadUrl("file:///android_asset/test.html");
        my_webView.loadUrl("file:///android_asset/test2.html");

        my_webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Uri uri = Uri.parse(url);
                Log.e(TAG, "scheme = " + uri.getScheme() );
                Log.e(TAG, "authority = " + uri.getAuthority() );

                if(uri.getScheme().equals("js")){
                    if(uri.getAuthority().equals("webView")){
                        /*Set<String> paramSet = uri.getQueryParameterNames();
                        for(String param: paramSet){
                            String value = uri.getQueryParameter(param);
                            Log.e(TAG, "param = "+ param + " value = "+ value);
                        }*/

                        //跳转到商品展示页面
                        String func = uri.getQueryParameter("func");
                        if(func.equals("showData")){
                            //获取id并传递
                            String id = uri.getQueryParameter("id");
                            Intent intent = new Intent(MainActivity.this, ActivityB.class);
                            intent.putExtra("ID", id);
                            startActivity(intent);
                        }
                    }
                }
                return true;
            }
        });

        //js响应
        my_webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
                                      final JsPromptResult result) {
                Uri uri = Uri.parse(message);
                if (uri.getScheme().equals("js")) {
                    if (uri.getAuthority().equals("webView")) {
                        String func = uri.getQueryParameter("func");
                        if (func.equals("getName")) {
                            final EditText editTxt = new EditText(MainActivity.this);
                            new AlertDialog.Builder(MainActivity.this)
                                    .setTitle("请输入你的名字")
                                    .setView(editTxt)
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            String name = editTxt.getText().toString();
                                            result.confirm(name);
                                            dialog.cancel();
                                        }
                                    })
                                    .create().show();
                        }
                    }
                }
                return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                Uri uri = Uri.parse(message);
                if(uri.getScheme().equals("js")){
                    if(uri.getAuthority().equals("webView")){
                        String func = uri.getQueryParameter("func");
                        if(func.equals("getInfo")){
                            new AlertDialog.Builder(MainActivity.this)
                                    .setTitle("你是帅哥吗？")
                                    .setPositiveButton("是", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            result.confirm();
                                            dialog.cancel();
                                        }
                                    })
                                    .setNegativeButton("否", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            result.cancel();
                                            dialog.cancel();
                                        }
                                    })
                                    .create().show();
                        }
                    }
                }
                return true;
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                Log.e(TAG, "message = " + message);
                Uri uri = Uri.parse(message);
                if(uri.getScheme().equals("js")){
                    if(uri.getAuthority().equals("webView")){
                        String func = uri.getQueryParameter("func");
                        if(func.equals("getInfo")){
                            String id = uri.getQueryParameter("id");
                            Intent intent = new Intent(MainActivity.this, ActivityB.class);
                            intent.putExtra("ID", id);
                            startActivity(intent);
                        }
                    }
                }


                /*new AlertDialog.Builder(MainActivity.this)
                        .setTitle("Android使用:")
                        .setMessage(message)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                result.confirm();
                            }
                        })
                        .create()
                        .show();*/
                return true;
            }
        });

        //JS调用Android代码
        //通过WebView的addJavascriptInterface（）进行对象映射
        my_webView.addJavascriptInterface(new JsToAndroid(MainActivity.this),"test");

        //跳转
        my_webView.addJavascriptInterface(new Jump(MainActivity.this),"startAnotherActivity");

        btn_callJS.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //android调用js第一种 通过WebView的loadUrl（）
//                my_webView.loadUrl("javascript:callJS()");

                //第二种 通过WebView的evaluateJavascript()
                my_webView.evaluateJavascript("javascript:getCircleArea(5)",
                        new ValueCallback<String>() {
                            @Override
                            public void onReceiveValue(String value) {
                                Log.e("MainActivity", "圆的面积: "+ value );
                                Toast.makeText(MainActivity.this,
                                        "圆的面积: "+ value,
                                        Toast.LENGTH_SHORT).show();
                            }
                        });
            }
        });
    }
}
